import Vue from "vue";
import Vuex from "vuex";
import axios from 'axios'
import appApi from '../../utils/api'
// import router from '../router'
Vue.use(Vuex);
export default {
    namespaced: true,
    state: {
        books: {
            InterestAssociation:[],    //用于根据检索词获取读者感兴趣的关联内容
            Namedparent: {
                key: '5',
                name: 'NewEbook'
            },
            detailquery: {          //电子书详情参数
                searchtitle: '',
                id: ''
            },
            loading_over: false,
            rscontype: false,
            showdetail: false,
            bookinfo_already_show: false,
            show_sider: false,
            show_pagination: false,
            fieldsAllow: {      //搜索数目类型
                sortFields: [
                    { id: "relevance", name: "相关度排序" },
                    { id: "title", name: "书名" },
                    { id: "author", name: "责任者" },
                    { id: "publisher", name: "出版社" },
                    { id: "pubYear", name: "出版日期" },
                    { id: "callNo", name: "索书号" },
                ],
                searchAdvCode: { title: "title", author: "author", publisher: "publisher", isbn: "isbn" },
                searchKeys: [
                    { "id": "books_all", name: "任意词" },
                    { "id": "title", name: "书名" },
                    { "id": "author", name: "作者" },
                    { "id": "publisher", name: "出版社" },
                    { "id": "isbn", name: "ISBN" }
                ],
                sortTypes: ["desc", "asc"],
                pageSizeOptions: ['10', '20', '50', '100'],
                defaultPageSize: 20,
            },
            // qs: 请求参数
            qs: {
                Epac: {
                    arr_fieldLists: [],
                    "searchWords":[
                        {
                            "fieldList":[
                                {
                                    "fieldCode":"books_all",
                                    "fieldValue":"",
                                }
                            ]
                        }
                    ],
                    // filters ，是左侧切面条件选择的条件
                    "filters":[],
                    "limiter":[
                    ],
                    "sortField":"relevance",
                    "sortType":"desc",
                    "pageSize":20,
                    "pageCount":1,
                    "locale":"zh_CN"
                },
                searchWords: [{
                    fieldList: [
                        { fieldCode: "01", fieldValue: "红楼梦" }
                    ],
                }],
                filters: [
                    // {
                    //     "fieldName":"src",
                    //     "values":[
                    //         "cxstar"
                    //     ]
                    // },
                    // {
                    //     "fieldName":"pubYear",
                    //     "values":[
                    //         "2016"
                    //     ]
                    // }
                ],
                tags: [],
                limiter: [],
                sortField: "relevance",
                sortType: "desc",
                pageSize: 20,
                pageCount: 1, //这个是第几页
                locale: "zh_CN",
                first: true
            },
            isbn: {
                searchWords: [{
                    fieldList: [{
                        fieldCode: "books_all",
                        fieldValue: '',
                        fieldConj: "OR"
                    }]
                }],
                filters: [],
                unionFilters: [],
                limiter: [],
                sortField: "relevance",
                sortType: "desc",
                locale: "zh_CN",
                pageSize: 20,
                pageCount: 1
            },
            // rs:检索结果

            rs: {
                total: 180,
                content: [],
                facetsList: [
                ],

                "filters": [
                    { "fieldName": "subjectFacet", "values": ["红楼梦", "文学研究"] },
                    { "fieldName": "locationFacet", "values": ["03005"] }
                ],
                "limiter": [],
                "sortField": "relevance",
                "sortType": "desc",
                "pageSize": 20,
                "pageCount": 1,
                "locale": "zh_CN",
                "first": true,
            },

        },
    },
    mutations: {
         // 用于根据检索词获取读者感兴趣的关联内容
        changeganxingqu(state, con){
            state.books.InterestAssociation = con;
        },
        // 获取跳转电子书详情参数
        ChangeDetailQuery(state, status) {
            state.books.detailquery.searchtitle = status.searchtitle;
            state.books.detailquery.id = status.id;
        },
        // 判断是否打开侧边栏菜单
        BOOKINFO_ALREADY_SHOW(state, is_show) {
            state.books.bookinfo_already_show = is_show;
        },
        // 清空请求参数
        CLEAR_QS(state) {

            var qs = {
                Epac: {
                    arr_fieldLists:[],
                    "searchWords":[
                        {
                            "fieldList":[
                                {
                                    "fieldCode":"title",
                                    "fieldValue":"php",
                                }
                            ]
                        }
                    ],
                    // filters ，是左侧切面条件选择的条件
                    "filters":[
                        // {
                        //     "fieldName":"src",
                        //     "values":[
                        //         "cxstar"
                        //     ]
                        // },
                        // {
                        //     "fieldName":"pubYear",
                        //     "values":[
                        //         "2016"
                        //     ]
                        // }
                    ],
                    "limiter":[
                    ],
                    "sortField":"relevance",
                    "sortType":"desc",
                    "pageSize":20,
                    "pageCount":1,
                    "locale":"zh_CN"
                },
                searchWords: [{
                    fieldList: [
                        { fieldCode: "01", fieldValue: "红楼梦" },
                        // { "fieldCode": "", "fieldValue": "红楼梦", "fieldConj": "AND" },
                        // { "fieldCode": "04", "fieldValue": "曹雪芹", "fieldConj": "AND" }
                    ],
                }],
                filters: [
                    // { fieldName: "subjectFacet", values: ["红楼梦", "文学研究"] },
                    // { fieldName: "locationFacet", values: ["03005"] },
                ],
                tags: [],
                limiter: [],
                sortField: "relevance",
                sortType: "desc",
                pageSize: 20,
                pageCount: 1, //这个是第几页
                locale: "zh_CN",
                first: true
            };
            state.books.qs = qs;
            state.books.rs.filters = [];
        },
        // 获取返回的过滤条件
        UpdateQsFacets(state, facetsList) {
            state.books.qs.filters = facetsList;
        },
        // UpdateRsFacets(state, facetsList, indexs) {
        //     state.books.rs.facetsList[indexs].facetList = facetsList;
        // },
        UpdateRsFacets(state, facetsList) {
            state.books.rs.facetsList = facetsList;
        },
        // 获取总数
        UpdateRsTotal(state, total) {
            state.books.rs.total = total;
        },
        // 获取书籍列表内容
        UpdateRsContent(state, books) {
            state.books.rs.content = books;
        },
        ///
        /**
         * 更新qs 中的检索词
         * 1、更新keyword
         * 2、这里通通重置为第1页
         * 3、
         * searchWords: [
                    {
                        fieldList: [
                            { fieldCode: "", fieldValue: "红楼梦" },
                            { "fieldCode": "04", "fieldValue": "曹雪芹", "fieldConj": "AND" }
                        ],
                    }
                ],
         * @param {*} state 
         * @param {检索词，是} search_keyword 
         * 
         */
        // 获取搜索参数   关键字   页码
        UpdateQsSearchKeyWord(state, search_keyword) {
            this.commit(state.books.Namedparent.name + "/UpdateQsSearchKeyWordV2", search_keyword, 1);
        },
        // 获取搜索参数   关键字   页码
        UpdateQsSearchKeyWordV2(state, search_keyword, current_page) {
            // state.books.qs.searchWords[0].fieldList[0].fieldValue = search_keyword;
            state.books.qs.Epac.searchWords[0].fieldList[0].fieldValue = search_keyword;

            // state.books.qs.searchWords = [{
            //     fieldList: [
            //         { fieldCode: search_field_code, fieldValue: search_keyword },
            //     ],
            // }];
            var current_pages = current_page == undefined ? 1 : current_page;
            state.books.qs.Epac.pageCount =current_pages;
            state.books.qs.filters = [];
        },
        //高级检索条件，多个关键词
        UpdateQsSearchFieldListAdv(state, search_field_list) {
            state.books.qs.searchWords[0].fieldList = search_field_list;
            state.books.qs.Epac.fieldValue = search_field_list[0].fieldValue;
            state.books.qs.Epac.arr_fieldLists = search_field_list;
            state.books.qs.Epac.searchWords[0].fieldList = search_field_list;
        },
        // 年代限制 ["DT:1999/2021"] 这种格式
        UpdateQsLimiter(state, limiter) {
            state.books.qs.limiter = limiter;
            state.books.qs.Epac.limiter = limiter;
        },
        // 改变请求参数类型
        ChangeQsSearchField(state, search_field) {
            state.books.qs.Epac.fieldCode = search_field;
            state.books.qs.Epac.searchWords[0].fieldList[0].fieldCode = search_field;
        },
        // 获取搜索类型
        ChangeSortType(state, sortType) {
            state.books.qs.Epac.sortType = sortType;
        },
        // 获取排序类型
        ChangeSortField(state, sortField) {
            state.books.qs.Epac.sortField = sortField;
        },
        // 获取页码
        ChangeCurrentPage(state, currentPage) {
            state.books.qs.Epac.pageCount = currentPage;
        },
        // 获取页码
        ChangeCurrentPageWithOutSync(state, currentPage) {
            state.books.qs.Epac.pageCount = currentPage;
        },
        // 修改每页显示条数
        ChangePageSize(state, pageSize) {
            state.books.qs.pageSize = pageSize;
            state.books.rs.pageSize = pageSize;
            state.books.fieldsAllow.pageSize = pageSize;
            var current_page = state.books.qs.Epac.pageCount;
            var total = state.books.rs.total;
            if (current_page * pageSize > total) {
                current_page = Math.ceil(total / pageSize);
                this.commit("ChangeCurrentPage", current_page);
            }
        },
        // 清空数据列表
        ClearBooksContents(state) {
            state.books.rs.content = [];
        },
        // 判断是否显示页码
        SHOW_DETAIL(state, status) {
            state.books.showdetail = status;
        },
        // 判断是否显示侧边栏
        SHOW_SIDER(state, status) {
            state.books.show_sider = status;
        },
        // 判断是否显示页码
        SHOW_PAGINATION(state, status) {
            state.books.show_pagination = status;
        },
        // 添加书籍参数
        AddBook(state, {
            author,
            category,
            bisbn,
            isbn,
            pub_year,
            publisher,
            title,
            filetype,
            bookid,
            cover
        }) {
            var book = {
                author: author,
                category: category,
                bisbn: bisbn,
                isbn: isbn,
                pub_year: pub_year,
                publisher: publisher,
                title: title,
                filetype: filetype,
                bookid: bookid,
                cover: cover,
            };
            state.books.rs.content.push(book);
        },
        removeFilters(state, index) {
            // 移除弹窗
            state.dialogList.splice(index, 1);
        },
        // 获取侧边栏参数
        SearchSideUpdateFilters(state, { fieldName, value ,fieldNametxt,lable}, is_search_books) {
            //数据结构 { "fieldName": "subjectFacet", "values": ["红楼梦", "文学研究"] },
            //var filter_len = state.books.qs.filters.length;
            var findFilter = false;
            // 如果fieldName对应的fieldName如subjectFacet 是第一次添
            state.books.qs.Epac.arr_fieldLists.forEach(function(item, i) {
                var filter = item;
                if (filter.fieldCode == fieldName) {
                    findFilter = true;
                    state.books.qs.Epac.arr_fieldLists.splice(i, 1);
                    state.books.qs.Epac.filters.splice(i, 1);
                }
            });

            // for (var i = 0; i < filter_len; i++) {
            //     var filter = state.books.qs.filters[i];
            //     if (filter.fieldName == fieldName) {
            //         findFilter = true;
            //         var index = filter.values.indexOf(value);
            //         // 如果filter 中已经存在value，则之前为选中状态，现在要删除
            //         // 如果之前未选中，则现在要增加
            //         if (index >= 0) {
            //             filter.values.splice(index, 1);
            //             if (state.books.qs.filters[i].values.length == 0) {
            //                 state.books.qs.filters.splice(i, 1);
            //                 state.books.qs.Epac.arr_fieldLists.splice(i, 1);
            //             }
            //         } else {
            //             filter.values.push(value);
            //         }
            //         Vue.set(state.books.qs.filters, i, filter);
            //     }

            // }
            if (findFilter == false) {
                // state.books.qs.filters.push({ "fieldName": fieldName, "values": [value] });
                //    fieldCode: "",
                //    fieldConj: "OR",
                //    fieldValue: "",
                state.books.qs.Epac.arr_fieldLists.push({ fieldCode: fieldName, fieldValue: value, fieldConj: "AND",lable:lable ,fiedvaluetxt:fieldNametxt});
                state.books.qs.Epac.filters.push(
                    {
                        "fieldName":fieldName,
                        "values":[
                            value
                        ]
                    }
                );
               
            }
            // for (i = 0; i < filter_len; i++) {
            //     if (state.books.qs.filters[i].values.length == 0) {
            //         state.books.qs.filters.splice(i, 1);
            //     }
            // }
            is_search_books = true;
            if (is_search_books) {
                this.dispatch("NewEbook/SearchGetBooks")
            }
        },
        // 获取loading是否加载完成
        Changeloading(state, status) {
            state.books.loading_over = status;
        }
    },
    actions: {
        // 初始化获取书籍列表
        GetBooks(context) {
            context.state.books.loading_over = true;
            let flag = navigator.userAgent.match(
                /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i
            );
            appApi.NewEbookSearchGetlist(context.state.books.qs.Epac)
            .then(response => {
                var data = response.data.content;
                var x = data;
                if (response.status == 200) 
                    context.commit("UpdateRsFacets",  response.data.facetsList);
                    if (context.state.books.rs.content.length > 0) {
                        // context.commit("ClearBooksContents");
                        context.state.books.rs.content = [];
                    }
                    var book_length = x.length;
                    var books = [];
                    for (var i = 0; i < book_length; i++) {
                        var book = {
                            id: 0,
                            title: "",
                            author: "",
                            publisher: "",
                            publish_date: "",
                            pub_year: 0,
                            cover: "",
                            intro: "",
                            isbn: "",
                            bisbn: "",
                            category: "",
                            cates: "",
                            booktype: "",
                            filetype: "",
                            bookid: "",
                            assertId: "",
                            src: [],
                            view_count: 0,
                            extid: "",
                            ext: "",
                            muluText: "",
                            created_at: 0,
                            updated_at: 0,
                            pc_read: "",
                            pc_epub: "",
                            wx_read: "",
                            wx_epub: "",
                            read: '',
                            detail: "",
                            ebooklist: [],
                            urls:[],
                            srcarrname:[],
                            srcarrkey:[],
                            srcarrkeyhref:[],
                            sample1:[]
                        };
                        book.author = x[i].author;
                        book.category = x[i].category;
                        book.cates = x[i].classfy;  //分类
                        book.bisbn = x[i].isbn;
                        book.isbn = x[i].isbn;
                        book.pub_year = parseInt(x[i].pub_year);
                        book.publish_date = x[i].pubYearText;   //出版日期
                        book.publisher = x[i].publisher;
                        // 处理urls来源  start
                        var urls_arr = x[i].urls;
                        Object.keys(urls_arr).forEach(function(key){
                            book.srcarrname.push(key)
                            Object.keys(urls_arr[key]).forEach(function(key2){
                            Object.keys(urls_arr[key][key2]).forEach(function(key3){
                                book.srcarrkey.push(key3)
                                book.srcarrkeyhref.push(urls_arr[key][key2][key3])
                            })
                            })
                            }
                        )
                        
                            // 处理urls来源  end
                       // book.src = book.src;
                        book.title = x[i].title;
                        book.id = x[i].bookId;
                        book.filetype = x[i].fileType;
                        book.bookid = x[i].bookid;
                        book.intro = x[i].intro;
                        book.src = x[i].src;
                        book.urls = x[i].urls;
                        book.read = flag ? x[i].wx_read : x[i].pc_read;
                        var isbn = book.isbn;
                        if (isbn.indexOf(",") > 0) {

                            var isbns = isbn.split(",");
                            if (isbns.length > 1) {
                                isbn = isbns[0];
                                isbn = isbn.replace("-", "");
                            }
                        }
                        book.cover = x[i].cover;
                        books[i] = book;
                    }

                    for (let ins = 0; ins < books.length; ins++) {
                        var isbn_ = { "fieldCode": "05", fieldValue: "", "fieldConj": "OR" };
                        isbn_.fieldValue = books[ins].isbn.replace(/-/g, "");
                        context.state.books.isbn.searchWords[0].fieldList.push(isbn_)
                    }
                    context.dispatch('asyncFunc', books)
                    context.commit("SHOW_PAGINATION", true);
                    context.commit("SHOW_SIDER", true);
                    context.commit("UpdateRsTotal", parseInt(response.data.total));
            
                setTimeout(() => {
                    context.state.books.loading_over = false;
                }, 1000)
                context.state.books.rscontype = true;
            })
            .catch(function(error) {
                // 请求失败处理
                console.log("runoob", error);
            });
                       // 用于根据检索词获取读者感兴趣的关联内容 start
                    let params = {
                    key:context.state.books.qs.Epac.searchWords[0].fieldList[0].fieldValue,
                    page:1
                    }
                    appApi.InterestAssociation(params)
                    .then(res => {
                        if(res.status == 200){
                            context.state.books.InterestAssociation = res.data;
                            context.commit("changeganxingqu", res.data);
                        }
                    })
        },
        // 搜索书籍列表
        SearchGetBooks(context) {
            // 用于根据检索词获取读者感兴趣的关联内容 start
            let params = {
                key:context.state.books.qs.Epac.searchWords[0].fieldList[0].fieldValue,
                page:context.state.books.qs.Epac.pageCount
            }
            appApi.InterestAssociation(params)
            .then(res => {
                if(res.status == 200){
                    context.state.books.InterestAssociation = res.data;
                    context.commit("changeganxingqu", res.data);
                }
            })
            // 用于根据检索词获取读者感兴趣的关联内容 end

            context.state.books.loading_over = true;
            // 判断设备
            let flag = navigator.userAgent.match(
                /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i
            );
            appApi.NewEbookSearchGetlist(context.state.books.qs.Epac)
            .then(response => {
                var data = response.data.content;
                var x = data;
                if (response.status == 200) {
                    context.commit("UpdateRsFacets",  response.data.facetsList);
                    if (context.state.books.rs.content.length > 0) {
                        context.state.books.rs.content = [];
                    }
                    var book_length = x.length;
                    var books = [];
                    for (var i = 0; i < book_length; i++) {
                        var book = {
                            id: 0,
                            title: "",
                            author: "",
                            publisher: "",
                            publish_date: "",
                            pub_year: 0,
                            cover: "",
                            intro: "",
                            isbn: "",
                            bisbn: "",
                            category: "",
                            cates: "",
                            booktype: "",
                            filetype: "",
                            bookid: "",
                            assertId: "",
                            src: "",
                            view_count: 0,
                            extid: "",
                            ext: "",
                            muluText: "",
                            created_at: 0,
                            updated_at: 0,
                            pc_read: "",
                            pc_epub: "",
                            wx_read: "",
                            wx_epub: "",
                            detail: "",
                            urls:[],
                            srcarrname:[],
                            srcarrkey:[],
                            srcarrkeyhref:[],
                            sample1:[]
                        };
                        book.author = x[i].author;
                        book.category = x[i].category;
                        book.cates = x[i].cates;
                        book.bisbn = x[i].bisbn;
                        book.isbn = x[i].isbn;
                        book.pub_year = parseInt(x[i].pub_year);
                        book.publish_date = x[i].publish_date;
                        book.publisher = x[i].publisher;
                        // 处理urls来源  start
                        var urls_arr = x[i].urls;
                        Object.keys(urls_arr).forEach(function(key){
                            book.srcarrname.push(key)
                            Object.keys(urls_arr[key]).forEach(function(key2){
                            Object.keys(urls_arr[key][key2]).forEach(function(key3){
                                book.srcarrkey.push(key3)
                                book.srcarrkeyhref.push(urls_arr[key][key2][key3])
                            })
                            })
                            }
                        )
                        // console.log(book)
                            // 处理urls来源  end
                        // book.src = book.src;
                        book.title = x[i].title;
                        book.id = x[i].bookId;
                        book.filetype = x[i].filetype;
                        book.bookid = x[i].bookid;
                        book.intro = x[i].intro;
                        book.src = x[i].src;
                        book.read = flag ? x[i].wx_read : x[i].pc_read;
                        var isbn = book.isbn;
                        if (isbn.indexOf(",") > 0) {

                            var isbns = isbn.split(",");
                            if (isbns.length > 1) {
                                isbn = isbns[0];
                                isbn = isbn.replace("-", "");
                            }
                        }
                        book.cover = x[i].cover;
                        books[i] = book;
                    }
                    for (let ins = 0; ins < books.length; ins++) {
                        var isbn_ = { "fieldCode": "05", fieldValue: "", "fieldConj": "OR" };
                        isbn_.fieldValue = books[ins].isbn.replace(/-/g, "");
                        context.state.books.isbn.searchWords[0].fieldList.push(isbn_)
                    }
                    context.dispatch('asyncFunc', books)
                    context.commit("SHOW_PAGINATION", true);
                    context.commit("SHOW_SIDER", true);
                    context.commit("UpdateRsTotal", parseInt(response.data.total));
                    setTimeout(() => {
                        context.state.books.loading_over = false;
                    }, 1000)
                }
            })
            .catch(function(error) {
                // 请求失败处理
                console.log("runoob", error);
            });
        },
        // 电子书检索对应纸书
        asyncFunc(context, books) {
            context.state.books.isbn.searchWords[0].fieldList = context.state.books.isbn.searchWords[0].fieldList.filter(function(s) {
                return s && s.fieldValue.trim();
            });
            // context.state.books.isbn.searchWords[0].fieldList[0].fieldValue = books.books[books.ins].isbn.replace(/-/g, "");
            return new Promise((resolve) => {
                setTimeout(() => {
                    appApi.Ebookgetpagerbook(context.state.books.isbn)
                        .then(res => {
                            if (res.status == 200 && res.data) {
                                for (var i = 0; i < books.length; i++) {
                                    for (var j = 0; j < res.data.content.length; j++) {
                                        if (books[i].isbn.replace(/-/g, "") == res.data.content[j].isbn.replace(/-/g, "")) {
                                            books[i].ebooklist = res.data.content[j];

                                        }
                                    }
                                }
                                context.commit("UpdateRsContent", books);
                            }
                        })

                        let isbn_arr = '';
                        books.forEach((item)=>{
                            return isbn_arr +=item.isbn+','
                        })
                        // 根据isbn号获取每本书相应的关联内容
                        axios.get('./static/config.json').then((rese) => {
                            if(rese.status == 200){
                                for(var i = 0;i<rese.data.isbnguanlian.length;i++){
                                    axios.get(rese.data.BaseUrl_ + rese.data.isbnguanlian[i] + isbn_arr.substr(0, isbn_arr.length - 1))
                                        .then(res => {
                                              if (res.status == 200 && res.data) {
                                                res.data.forEach((item1,j)=>{
                                                    item1.key = j;
                                                    books.forEach((item,i)=>{
                                                        if(item1.isbn == item.isbn){
                                                            books[i].sample1.push(res.data[j])
                                                        }
                                                    })
                                                })
                                                context.commit("UpdateRsContent", books);
                                            }
                                        })
                                        .catch(err => {
                                          console.log(err)
                                        })
                                }
                            }
                        })
                        // appApi.isbnguanlian(isbn_arr.substr(0, isbn_arr.length - 1))
                        // .then(res => {
                        //     if (res.status == 200 && res.data) {
                        //         res.data.forEach((item1,j)=>{
                        //             item1.key = j;
                        //             books.forEach((item,i)=>{
                        //                 if(item1.isbn == item.isbn){
                        //                     books[i].sample1.push(res.data[j])
                        //                 }
                        //             })
                        //         })
                        //          context.commit("UpdateRsContent", books);
                        //     }
                        // })
                    resolve()
                }, 1)
            })
        }
    },
    getters: {
        // getQS: state => {
        //     return state.books.qs;
        //     // return state.books.filter(todo => todo.done)
        // }
    }
}